package cn.gqr.service.Impl;

import cn.gqr.entity.*;
import cn.gqr.mapper.CartMapper;
import cn.gqr.service.CartService;
import cn.gqr.service.OrderService;
import cn.gqr.tool.GetUser;
import cn.gqr.tool.RespJson;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    CartMapper cartMapper;
    @Autowired
    OrderService orderService;

    @Override
    public List<CartBook> findAll(int uid) {
        return cartMapper.findAll(uid);
    }

    @Override
    @Transactional
    public Map<String,Object> addCart2Order(Order order,List<OrderItem> lst) {

        //添加订单
        if(cartMapper.addOrder(order)==0){
            return RespJson.pack(500, "成功接收到数据, 但更新订单失败 ....", null);
        }

        //添加订单明细
        for (OrderItem orditem : lst) {
            orditem.setOrdid(order.getOrdid());
            int i = cartMapper.addOrderItem(orditem);
            //删除购物车
            cartMapper.delByUidBookId(order.getUid(),orditem.getBookid());
            if(i==0) return RespJson.pack(500, "成功接收到数据, 但更新订单失败 ....", null);
        }

        //查询订单返回订单
        Order orderObj = orderService.findByIdOrder(order.getOrdid());

        return RespJson.pack(200,"成功接收到数据, 并产生订单 ....",orderObj);
    }

    @Override
    public Map<String,Object> addCart(Cart cart) {
        //获取用户id
        int uid = ((User) GetUser.getUser()).getId();
        cart.setUid(uid);
        //根据uid和bookid进行修改num 如果修改成功表示这个购物车存在 num+1
        //如果不成功 表示不存在 进行添加购物车操作
        System.out.println(cart);
        int i = cartMapper.updByUidBookId(uid, cart.getBookid());
        if(i==0){
            i =  cartMapper.addCart(cart);
        }
        return RespJson.pack(200,i>0?"添加购物车成功":"添加购物车失败",i);

    }

    //删除购物车
    @Override
    public int delCart(int id) {
        return cartMapper.delById(id);
    }


}
